<?php

require_once (SERVER_ROOT . '/controllers/' . 'admin.php');
require_once (SERVER_ROOT . '/authenticate/' . 'Authenticator.php');

class GerenteController extends AdminController {

    private $usuarioDAO;
    private $gerente;

    public function __construct() {
        $this->usuarioDAO = new UsuarioDAO();
        $this->gerente = Authenticator::getUser();
    }

    public function listAllByType($p) {
        $page = $p['page'];
        $limit = $p['rows'];
        $sidx = $p['sidx'];
        $sord = $p['sord'];
        $search_field = $p['searchField'];
        $search_string = $p['searchString'];
        $search_oper = $p['searchOper'];
        if (!$sidx)
            $sidx = 1;
        $count = $this->usuarioDAO->countByOffice($p['type'], $this->gerente->id_escritorio);
        $total_pages = ($count > 0 ? ceil($count / $limit) : $total_pages = 0);
        if ($page > $total_pages)
            $page = $total_pages;
        $start = $limit * $page - $limit;
        if ($start < 0)
            $start = 0;
        if ($search_string == "") {
            $result = $this->usuarioDAO->findAllByOffice($p['type'], $sidx, $sord, $start, $limit, $this->gerente->id_escritorio);
        } else {
            $result = $this->usuarioDAO->findAllByOfficeWithFilters($p['type'], $sidx, $sord, $start, $limit, $this->gerente->id_escritorio, $search_field, $search_string, $search_oper);
        }
        $response->page = $page;
        $response->total = $total_pages;
        $response->records = $count;
        for ($i = 0; $i < count($result); $i++) {
            $row = $result[$i];
            $response->rows[$i]['id'] = $row['id_usuario'];
            $response->rows[$i]['cell'] = array($row['id_usuario'], $row['id_escritorio'], $row['nome'], $row['endereco'], $row['cidade'], $row['cep'], $row['telefone_fixo'], $row['telefone_movel'], $row['email'], $row['estado'], $row['rg'], $row['cpf'], $row['data_nascimento'], $row['status'], '');
        }
        echo json_encode($response);
    }

}
